import React, { Component } from 'react';
import { toJS } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter, Link, Route } from 'react-router-dom';
import { Flex, SearchBar, Tools, Icon, Avatar, Popover, ActionSheet, Toast, Modal, Tag } from 'weaver-mobile';
import { ListViewPage, SearchPage, SearchAdvanced } from 'weaver-mobile-page';
import classnames from 'classnames';
import QueueAnim from 'rc-queue-anim';

import { listRoute, listParams } from './util';
import { searchToQuery,getFontColorFromBgHex, doConfirm, compareParams, isHighlight } from '../../util';
import NavBar from '../widget/NavBar';
import ActionButtons from '../widget/ActionButtons';
import View from '../view/View';
import New from '../new/New';
import SetTodo from '../widget/todo/SetTodo';
import MoveTo from '../widget/MoveTo';
import SetTag from '../widget/SetTag';
import BackTop from '../../public/back-to-top';

const getLabel = Tools.getLabel;
const alert = Modal.alert;

function closest(el, selector) {
  const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
  while (el) {
    if (matchesSelector.call(el, selector)) {
      return el;
    }
    el = el.parentElement;
  }
  return null;
}

@inject('listStore')
@withRouter
@observer
export default class List extends Component {
  static defaultProps = {
    prefixCls: 'email-list',
  }

  constructor(props) {
    super(props);
    this.setActiveKey();
    this.state = {
      mailId: '', // 传给view页面的id
      readStatus: 0,
      isSpaceFull:false,
      defaultParams: {},
    }
    this.getEmailSize();
  }

  //取邮件剩余空间
  getEmailSize = () => {
    Tools.callApi({url: '/api/email/folder/getEmailSize', method: 'GET'}).then(res => {
      const { remainspace } = res;
      if(parseFloat(remainspace)<=parseFloat(0)){
        this.setState({isSpaceFull: true})
      }
    })
  }

  componentDidMount() {
    this.setActiveKey();
    const { location: {search}, listStore } = this.props;
    const { searchAdvancedStore, searchParams, activeKey } = listStore;
    const list = this.props.listStore.getListStore();
    if (list) {
      list.listViewStore.setState({ template: { default: [{ key: 'col', render: () => '', }] } });
    }
    if (searchAdvancedStore) {
      searchAdvancedStore.form.resetConditions();
      const params = { ...toJS(searchParams), ...searchToQuery(search),...listParams[activeKey] };
      searchAdvancedStore.getData({
        url: '/api/email/list/getListCondition',
        params: params,
      }).then((form) => {
        this.setState({ defaultParams: form.formParams })
        let updateParams = {};
        for (let key in params) {
          updateParams[key] = {value: params[key]};
        }
        form.updateFields(updateParams);
        listStore.onSearch({current: 1});
      });
    } else {
      listStore.onSearch({current: 1});
    }
    
    // 收信
    if (activeKey === 'inbox') {
      //空间满，外部邮件不允许收信
      if(!this.state.isSpaceFull){
        listStore.initReceiveLetterInterval();
        listStore.receiveLetter();
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    const {listStore} = this.props;
    if (this.props.location.pathname !== nextProps.location.pathname) {
      const prevActiveKey = listStore.activeKey;
      this.setActiveKey(nextProps);
      const currentActiveKey = listStore.activeKey;
      if (prevActiveKey === 'inbox' && currentActiveKey !== 'inbox') {
        listStore.clearReceiveLetterInterval();
      } else if (prevActiveKey !== 'inbox' && currentActiveKey === 'inbox') {
         //空间满，外部邮件不允许收信
        if(!this.state.isSpaceFull){
          listStore.initReceiveLetterInterval();
          listStore.receiveLetter();
        }
      }
    }
    if (this.props.location.search !== nextProps.location.search) {
      listStore.setState({locationSearch: nextProps.location.search});
    }
    if (this.props.location.pathname.match(/\/([^/]+)$/)[0] === '/new' && nextProps.history.action === 'POP') {
      listStore.onSearch({current: 1});
    }
  }
  
  componentWillUnmount() {
    const { listStore } = this.props;
    const list = this.props.listStore.getListStore();
    if (list) {
      list.listViewStore.clearData();
    }
    listStore.setState({ showBatch: false, showCheck: false });
    ActionSheet.close();
    list.listViewStore.setState({ selectedRowKeys: [] });
    listStore.clearReceiveLetterInterval();
    if (this.modal && typeof this.modal.close === 'function') this.modal.close();
  }

  setActiveKey = (props) => {
    const { location: { pathname }, listStore } = props || this.props;
    if (/^\/[^/]+\/?/.test(pathname)) {
      const id = pathname.match(/^\/[^/]+/)[0].replace(/^\//, '');
      if (listRoute.some(r => r === id)) {
        listStore.setState({ activeKey: id });
        listStore.addListStore({ id, route: pathname });
      }
    }
  }

  getRowProps = (rowData) => {
    const { prefixCls, listStore } = this.props;
    const { showCheck, setStar, deleteEmail, withSwipeAction, onSearch, updateListData, activeKey } = listStore;
    const { starred } = rowData;
    const preClx = `${prefixCls}-swipe-action`;
    const needSearchPage = ['star', 'doing', 'tag', 'inner']
    const swipeActionProps = {
      right: [
        {
          text: getLabel(17499, '更多'),
          onPress: (data) => {
            this.showActionSheet(data)
          },
          className: `${preClx} ${preClx}-more`,
        },
        {
          text: starred ? getLabel(387793, '取消标星') : getLabel(382626, '标星'),
          onPress: (data) => {
            setStar({ mailIds: data.id, star: starred ? 0 : 1 });
          },
          className: `${preClx} ${preClx}-star`,
        },
        {
          text: getLabel(91, '删除'),
          onPress: (data) => {
            doConfirm(getLabel(15097, '确定要删除吗？'), '', () => {
              const folderIds = ['-2', '-3'];
              deleteEmail({ mailIds: data.id, operate: folderIds.includes(data.folderid) ? 'deletePermanently' : 'delete' })
                .then(res => {
                  if (needSearchPage.includes(activeKey) && data.folderid !== '-3') { // 需要更新的列表部分走接口刷新操作
                    onSearch({current: 1});
                  } else {
                    updateListData(data.id, {}, true)
                  }
                })
            });
          },
          className: `${preClx} ${preClx}-delete`,
        },
      ],
    }
    return {
      withSwipeAction,
      swipeActionProps,
      showCheck,
    };
  }

  showActionSheet = (data) => {
    this.setState({ mailId: data.id });
    const { history, listStore: { path, completeWaitdeal, getListStore } } = this.props;
    const list = getListStore();
    const func = () => this.setState({ mailId: data.id });
    let BUTTONS = [
      {
        content: data.waitdeal === 0 ? getLabel('384240','设置待办') : getLabel('386276','设置完成'),
        onClick: () => {
          func();
          data.waitdeal === 0 ? history.push(`${path}/todo`) :
          completeWaitdeal({ mailIds: data.id });
        },
      },
      {
        content: getLabel('30929','标记为'),
        onClick: () => {
          func();
          history.push(`${path}/setTag`);
        }
      }
    ];
    if(list.id && list.id !== 'draft') {
      BUTTONS = [...BUTTONS, {
        content: getLabel('81298','移动到'),
        onClick: () => {
          func();
          history.push(`${path}/moveTo`);
        }
      }]
    }
    BUTTONS = [...BUTTONS, {
      content: getLabel('31129','取消'),
    }]
    return ActionSheet.showActionSheetWithOptions({
      options: BUTTONS,
      maskClosable: true,
      'data-seed': 'logId',
      cancelButtonIndex: BUTTONS.length - 1,
      onTouchStart: e => e.preventDefault(),
    });
  }

  batchOperate = (callback) => { // 批量操作是否选择了邮件的判断
    const list = this.props.listStore.getListStore();
    const { listViewStore } = list;
    const selectedRowKeys = toJS(listViewStore.selectedRowKeys);
    if (selectedRowKeys.length === 0) {
      Toast.info('请选择邮件!', 1);
      return;
    } else {
      if (callback) callback(selectedRowKeys);
    }
  }
  
  // 移动到
  moveTo = (keys, datas) => {
    if (keys.length === 0) return;
    const { history, listStore: { operateUserMailFolder, showCheck, activeKey, folderid, onSearch, updateListState, updateListData } } = this.props;
    const needSearchPage = ['star', 'doing', 'tag', 'inner']
    if (activeKey === 'folder') {
      if (datas.filter(data => data.id === folderid).length > 0) { // 文件夹批量操作的情况下，用id判断
        Toast.info(getLabel(384182, '邮件已经在您要移动的文件夹了，不能重复移动！'));
        return;
      }
    } else if ((activeKey !== 'folder' || !showCheck) && datas.filter(data => data.key === activeKey).length > 0) {
      Toast.info(getLabel(384182, '邮件已经在您要移动的文件夹了，不能重复移动！'));
      return;
    }
    let res = operateUserMailFolder({
      operation: 'move',
      mailIds: this.getMailId(),
      folderId: keys.join(','),
      isBatch: showCheck ? 1 : 0,
    })
    if (res) {
      if (showCheck) { // 批量操作
        onSearch({current: 1});
        updateListState();
      } else { // 列表中单条更多中的移动到
        if (needSearchPage.includes(activeKey)) { // 需要更新的列表部分走接口刷新操作
          onSearch({current: 1});
        } else {
          updateListData(this.getMailId(), {}, true)
        }
      }
      history.go(-1);
    }
  }

  // 设置代办
  todo = (datas) => {
    const { history, listStore: { updateListData } } = this.props;
    updateListData(this.getMailId(), { waitdeal: 1, waitdealBean: { ...datas } });
    history.go(-1);
  }

  getMailId = () => {
    const { listStore: { getListStore, showCheck } } = this.props;
    const list = getListStore();
    const { listViewStore: { selectedRowKeys } } = list;
    const id = showCheck ? toJS(selectedRowKeys).join(',') : this.state.mailId;
    return id;
  }

  // 标记为
  setTag = (datas, tagList = {}) => {
	/* 	if (datas.length === 0) return;
		if (!this.getMailId()) { //编辑，删除标签后返回批量操作页面时，会刷新列表，导致之前选中的id无法保存。
			Toast.info('请选择邮件!', 1);
      return;
    } */
		
    const { history, listStore: { markEmailToByMobile, showCheck, onSearch, activeKey } } = this.props;
    let array = {};
    const fiflterData = tagList && tagList.groupItems && tagList.groupItems.length > 0 && datas.filter(v => v.key === 'tagManager').length === 0
    if (fiflterData) {
      this.modal = alert(getLabel('504597','您的操作会删除所有标签'), getLabel('82017','确认删除？'),[
        {
          text: getLabel('31129','取消'),
          onPress: () => { return; }
        },
        {
          text: getLabel('33703','确认'),
          onPress: () => {
            array = datas.map(data => {
              return {
                key: data.key,
                value: data.id,
                mailIds: this.getMailId(),
                operation: data.key === 'tagManager' ? 'addLabelByMobile' : '',
              }
            });
            array = [...array, {
              key: 'clearAll',
              value: '',
              mailIds: this.getMailId(),
              operation: 'clearAll',
            }]
            markEmailToByMobile({ markArray: JSON.stringify(array), from: 'list', isBatch: showCheck ? 1 : 0 }, () => {
              onSearch({current: 1}); // 删除所有标签时刷新列表
              history.go(-1);
            });
          }
        }
      ])
    }else{
      array = datas.map(data => {
        return {
          key: data.key,
          value: data.id,
          mailIds: this.getMailId(),
          operation: data.key === 'tagManager' ? 'addLabelByMobile' : '',
        }
      });
      markEmailToByMobile({ markArray: JSON.stringify(array), from: 'list', isBatch: showCheck ? 1 : 0 }, () => {
        if (activeKey === 'tag') { // 在标签列表中批量操作可能会有删除动作，故刷新列表
          onSearch({current: 1});
        }
        history.go(-1);
      });
    }
  }
  
  getActionButtons = (id) => {
    const { history, listStore: { path } } = this.props;
    const buttons = [
      {
        title: getLabel('384240','设置待办'),
        key: "todo",
        icon: <Icon type="blog-chidao" />,
        onPress: () => this.batchOperate(() => history.push(`${path}/todo`)),
      },
      {
        title: getLabel('30929','标记为'),
        key: "mark",
        icon: <Icon type="mail-marked-as" />,
        onPress: () => this.batchOperate(() => history.push(`${path}/setTag`)),
      },
    ];
    
    if(id&&id!='draft'){
      buttons.push(
        {
          title: getLabel('81298','移动到'),
          key: "move",
          icon: <Icon type="mail-move-to" />,
          onPress: () => this.batchOperate(() => history.push(`${path}/moveTo`)),
        }
      )
    }
    buttons.push(
      {
        title: getLabel(91, '删除'),
        key: "delete",
        icon: <Icon type="delete" />,
        onPress: () => this.shwoDeletcActionSheet(),
      }
    )
    return buttons;
  }

  shwoDeletcActionSheet = () => {
    const { listStore: { deleteEmail, activeKey, showCheck, onSearch, updateListData, updateListState } } = this.props;
    let BUTTONS = [
      {
        content: getLabel(91, '删除'),
        onClick: () => {
          this.batchOperate((selectedRowKeys) => {
            this.modal = doConfirm(getLabel('15097','确定要删除吗？'), '', () => {
              deleteEmail({ mailIds: selectedRowKeys.join(','), operate: 'delete' })
                .then(res => {
                  if (res.api_status) {
                    if (showCheck) { // 批量操作
                      onSearch({current: 1});
                      updateListState()
                    } else {
                      updateListData(selectedRowKeys.join(','), {}, true);
                    }
                  }
                })
            });
          });
        },
      },
      {
        content: getLabel('2031','永久删除'),
        onClick: () => {
          this.batchOperate((selectedRowKeys) => {
            this.modal = doConfirm(getLabel('15097','确定要删除吗？'), '', () => {
              deleteEmail({ mailIds: selectedRowKeys.join(','), operate: 'deletePermanently' })
                .then(result => {
                  if (result.api_status) {
                    if (showCheck) { // 批量操作
                      onSearch({current: 1});
                      updateListState()
                    } else {
                      updateListData(selectedRowKeys.join(','), {}, true);
                    }
                  }
                })
            });
          });
        },
      },
      {
        content: getLabel('31129','取消'),
      },
    ];

    //垃圾箱 && 草稿箱 只需要永久删除
    if(activeKey ==='deleted'||activeKey ==='draft'){
      BUTTONS = [
        {
          content: getLabel('2031','永久删除'),
          onClick: () => {
            this.batchOperate((selectedRowKeys) => {
              this.modal = doConfirm(getLabel('15097','确定要删除吗？'), '', () => {
                deleteEmail({ mailIds: selectedRowKeys.join(','), operate: 'deletePermanently' })
                  .then(res => {
                    if (showCheck) { // 批量操作
                      onSearch({current: 1});
                      updateListState()
                    } else {
                      updateListData(selectedRowKeys.join(','), {}, true);
                    }
                  })
              });
            });
          },
        },
        {
          content: getLabel('31129','取消'),
        },
      ];
    }

    return ActionSheet.showActionSheetWithOptions({
      options: BUTTONS,
      maskClosable: true,
      'data-seed': 'logId',
      cancelButtonIndex: BUTTONS.length - 1,
      onTouchStart: e => e.preventDefault(),
    });
  }

  getTemplate = () => {
    const { prefixCls } = this.props;
    const template = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const list = this.props.listStore.getListStore();
          const { columns } = list.listViewStore;
          const isToSpan = columns.some(col => col.dataIndex === 'toSpan');
          const {
            senddateSpan, subject, content, hasAttachment, labels, id,
            waitdeal, waitdealBean, starred, status, priority, belongtoType, 
            sendfromSpan: { imageUrl, realName, isInternal, userId },
            toSpan: { realName: toRealName },
            emailOcrInvoiceStatus,
            // flagSpan: { className },
          } = data;
          // 标签
          let tags = null;
          if (labels.length > 0) {
            tags = (
              <div className={`${prefixCls}-list-item-tags`}>
                {
                  labels.map(({ color, name, id: tagId }) => (
                    <Tag key={tagId} style={{ color: getFontColorFromBgHex(color),background: color }}>
                      {name}
                    </Tag>
                  ))
                }
              </div>
            );
          }
          // 待办
          let doing = null;
          if (waitdeal === 1 && waitdealBean) {
            doing = (
              <div
                className={`${prefixCls}-list-item-doing`}
                onClick={e => {
                  e.stopPropagation();
                }}
              >
                <Icon type="blog-bujiao" size="xxs" />
                {waitdealBean.waitdealtime}
              </div>
            );
          }
          // 星标和附件图标是否占位
          const iconNum = hasAttachment ^ starred ^ emailOcrInvoiceStatus;
          const accountCls = classnames(`${prefixCls}-list-item-account`, {
            [`${prefixCls}-list-item-account-${iconNum}`]: !(hasAttachment === 0 && starred === 0),
          });

          let name = isToSpan ? toRealName : realName;
          let reg = /^\s+|\s+$/g;
          let avatarname  = name.replace(reg,'').substring(0, 1).toUpperCase();

          let headerProps = {name: realName, url: imageUrl, userId: userId};
          let headerFlag = !isToSpan && isInternal === 1;

          return (
            <Flex key={id} className={`${prefixCls}-list-item`}>
              <Flex.Item style={{ flex: 'none' }}>
                {
                  headerFlag ?
                  <Avatar {...headerProps} />
                  : null

                }
                {
                  !headerFlag ?
                  <Avatar name={avatarname} url={imageUrl || ''} />
                  : null
                }
                
              </Flex.Item>
              <Flex.Item >
                <div className={accountCls}>
                  <div className='user-info'>
                    {status !== 1 && <span className={`${prefixCls}-list-item-unread`}/>}
                    {priority === '1' && <span className={`${prefixCls}-list-item-important`}>!</span>}
                    <span style={{ fontWeight: status === 1 ? 'normal' : 'bold' }}>{name}</span>
                  </div>
                  <div className={`${prefixCls}-list-item-account-extra`}>
                    {hasAttachment ? <Icon type="enclosure" size="xxs" /> : null}
                    {starred ? <Icon type="blog-xing" size="xxs" /> : null}
                    <div className={`${prefixCls}-list-item-account-time`} dangerouslySetInnerHTML={{ __html: senddateSpan }} />
                  </div>
                </div>
                <div className={`${prefixCls}-list-item-theme`}>
                  <div className={`${prefixCls}-list-item-subject`}>
                    {emailOcrInvoiceStatus ? <Icon color ={emailOcrInvoiceStatus === "1"?"#1BDD3F":"#F72B2B" }type={emailOcrInvoiceStatus === "1"?"finance-right":"finance-wrong"} size="xxs" />: null}
                    <span style={{ fontWeight: status === 1 ? 'normal' : 'bold' }} dangerouslySetInnerHTML={{ __html: subject }}/>
                  </div>
                  <div className='account-type'>
                    {
                      belongtoType === '1' ? <Icon type="zhuzhanghao"/> : 
                      belongtoType === '2' ? <Icon type="cizhanghao"/> :
                      ''
                    }
                  </div>
                </div>
                <div className={`${prefixCls}-list-item-content`} ><span>{content}</span></div>
                {tags}
                {doing}
              </Flex.Item>
            </Flex>
          );
        },
      }],
    };
    return template;
  }

  // SearchBar function
  onSearchBarFocus = () => {
    const { history, listStore } = this.props;
    const { activeKey, searchPageStore, searchHtPath } = listStore;
    history.push(searchHtPath);
    if (activeKey) {
      const key = `emailSearchHistory__${activeKey}`;
      let searchHistory = localStorage.getItem(key);
      searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
      searchPageStore.list.setState({ data: searchHistory });
    }
  }

  onSearchPageChange = (v) => {
    const { searchKey, setState, searchAdvancedStore } = this.props.listStore;
    setState({ searchParams: { [searchKey]: v } });
    if (searchAdvancedStore.form) {
      searchAdvancedStore.form.updateField(searchKey, v);
    }
  }

  onSearchPageClear = () => {
    const { activeKey, searchPageStore } = this.props.listStore;
    if (activeKey) {
      const key = `emailSearchHistory__${activeKey}`;
      localStorage.removeItem(key);
      searchPageStore.list.setState({ data: [] });
    }
  }

  // SearchAdvanced function
  onSearchAdvancedReset = () => {
    const { searchKey, searchParams, setState, activeKey, searchAdvancedStore : { form } } = this.props.listStore;
    setState({ searchParams: { ...searchParams, [searchKey]: '' } });

    // 标星、待办 重置的时候 不需要清空 默认的标星和待办
    if (activeKey === 'star') {
      form.updateFields({
        star: { value: '1' },
        menu_star: { value: '1'},
      });
    }
    if (activeKey === 'doing') {
      form.updateFields({
        waitdeal: { value: '1' },
        menu_waitdeal: { value: '1'},
      });
    }
  }

  onSearchAdvancedChagne = (c, value) => {
    const { searchKey, searchParams, setState } = this.props.listStore;
    if (c.domkey[0] === searchKey) {
      setState({ searchParams: { ...searchParams, [searchKey]: value } });
    }
  }
  onWrapTouchStart = (e) => {
    // fix touch to scroll background page on iOS
    if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
      return;
    }
    const pNode = closest(e.target, '.am-modal-content');
    if (!pNode) {
      e.preventDefault();
    }
  }

  render() {
    const list = this.props.listStore.getListStore();
    if (!list) return null;

    const { prefixCls, listStore, history } = this.props;
    const {
      activeKey,
      searchPageStore,
      searchAdPath,
      searchAdvancedStore,
      searchParams,
      searchKey,
      showBatch,
      showCheck,
      path,
      newParam,
      tip,
      unreceiveNum,
      updateListData,
    } = listStore;

    //console.info('activeKey',activeKey)
    const { listViewStore,id, listViewStore: { selectedRowKeys, isSelectedAll, selectNone, selectAll, updateDataSource } } = list;

    // Search Advanced
    const searchAdIconCls = `${prefixCls}-search-advanced-icon`;
    const searchAdIconProps = {
      type: 'filter-o',
      className: searchAdIconCls,
    };

    const { form } = searchAdvancedStore;
    // const compare = compareParams(toJS(form.formParams), toJS(this.state.defaultParams));
    const compare = isHighlight(searchAdvancedStore);
    if (form && compare) {
      searchAdIconProps.className = classnames(searchAdIconCls, `${searchAdIconCls}-unempty`);
      searchAdIconProps.type = 'filter-o-hot';
    }

    const more = (
      <Popover
        mask
        visible={showBatch}
        overlayClassName={`${prefixCls}-more-overlay`}
        overlay={[
          <Popover.Item key="batch" value="batch" data-seed="batch">{getLabel('500410',"批量操作")}</Popover.Item>,
          <Popover.Item key="markAllAsReaded">{getLabel('507778', '全部标为已读')}</Popover.Item>
        ]}
        onVisibleChange={v => listStore.setState({ showBatch: v })}
        onSelect={(item) => {
          if(item.key === 'markAllAsReaded'){
            let array =  [{
                key: item.key,
                value: '1',
                mailIds: "",
                operation: item.key,
              }]
            listStore.markEmailToByMobile({ markArray: JSON.stringify(array), from: 'list', isBatch: 1 }, () => {listStore.onSearch({current: 1})})
            listStore.setState({ showBatch: false });
          }else{
            listStore.setState({ showBatch: false, showCheck: true });
            updateDataSource();
          }
        }}
      >
        <Icon type="ellipsis" />
      </Popover>
    );

    const extraProps = {
      showExtraButton: true,
      extraButton: [
        { key: 'searchAd', show: <Link to={searchAdPath}><Icon {...searchAdIconProps} /></Link> },
        { key: 'more', show: more },
      ],
    };

    const checkAll = (showCheck ? (
      <div className={`${prefixCls}-all am-list-item`}>
        <span>
          <span
            className={`${prefixCls}-all-cancel`}
            onClick={() => {
              listStore.setState({ showCheck: false });
              listViewStore.setState({ selectedRowKeys: [] });
              updateDataSource();
            }}
          >{getLabel(31129, '取消')}</span>
          <span>{`${getLabel(31503, '已选择')}${selectedRowKeys.length} ${getLabel(83083, '封')}`}</span>
        </span>
        <span>
          <span
            className={`${prefixCls}-all-select`}
            onClick={() => isSelectedAll ? selectNone() : selectAll()}
          >{`${isSelectedAll ? getLabel(387379, '取消全选') : getLabel(556, '全选')}`}</span>
        </span>
      </div>
      ) : null
    );

    const wrapCls = classnames(prefixCls, `${prefixCls}-${activeKey}`);
    const showTip = activeKey === 'inbox' && unreceiveNum > 0;
    const listCls = classnames(`${prefixCls}-view`, showCheck ? `${prefixCls}-view-with-check` : '', showTip ? `${prefixCls}-view-with-tip` : '');
    const searchValue = searchParams[searchKey] || '';

    const moveToParams = {
      from: 'list',
      mailId: showCheck ? selectedRowKeys.join(',') : this.state.mailId,
      isBatch: showCheck ? 1 : 0,
    }
    return (
      <QueueAnim style={{height: '100%'}}>
        <div className={wrapCls} key="list">
          <SearchBar
            className={`${prefixCls}-search-bar`}
            value={searchValue}
            placeholder={getLabel(500351, '请输入关键字')}
            onFocus={this.onSearchBarFocus}
            {...extraProps}
          />
          {showTip &&
            <div className={`${prefixCls}-tip`} onClick={() => listStore.onSearch({current: 1})}>
              {getLabel(84535, '您有')}{unreceiveNum}{getLabel(501557, '封新邮件')}
            </div>
          }
          <SearchPage
            searchValue={searchValue}
            store={searchPageStore}
            rowKey="key"
            nameKey="name"
            type={1}
            onChange={this.onSearchPageChange}
            onSubmit={(v) => {
              this.onSearchPageChange(v);
              listStore.onSearch({current: 1});
            }}
            onClear={this.onSearchPageClear}
          />
          {checkAll}
          <div className={listCls}>
          <BackTop
            visibilityHeight='200'
            modal
            target='wm-list-view-page-modal-scrollview'
          >
            <ListViewPage.Normal
              store={list.listViewStore}
              getDataCustom={true}
              getTemplate={this.getTemplate}
              getRowProps={this.getRowProps}
              customHeight="100%"
              onEndReached={current => listStore.onSearch({current})}
              onRefresh={current => listStore.onSearch({current: 1})}
              onRowClick={item => {
                if (!showCheck) {
                  if (activeKey === 'draft' || item.folderid === '-2') {
                    listStore.setState({newParam: {id: item.id, flag: 4}});
                    updateListData(item.id, {})
                    history.push(`${path}/new`);
                  } else {
                    this.setState({ mailId: item.id, readStatus: item.status });
                    history.push(`${path}/view/${item.id}`);
                  }
                }
              }}
            />
          </BackTop>
          </div>
          <SearchAdvanced
            store={searchAdvancedStore}
            onSubmit={() => {listStore.onSearch({current: 1})}}
            onReset={this.onSearchAdvancedReset}
            onChange={this.onSearchAdvancedChagne}
          />
          {showCheck ?
            <ActionButtons data={this.getActionButtons(id)}/> :
            <NavBar
              onSelect={() => {
                listStore.setState({newParam: {}});
                history.push(`${path}/new`)
              }}
            />
          }
        </div>
        <Modal
          visible={tip.visible}
          transparent
          maskClosable={true}
          onClose={() => listStore.setState({tip:{visible: false}})}
          title={getLabel(25700, '错误信息')}
          footer={[{ text: getLabel(16631, '确认'), onPress: () => listStore.setState({tip:{visible: false}})}]}
          wrapProps={{ onTouchStart: this.onWrapTouchStart }}
        >
          <div style={{ height: 100, overflow: 'auto' }}>
            {tip.msg}
          </div>
        </Modal>
        <Route
          key="view"
          path={`${path}/view/:id`}
          render={() => {
            return (
              <View path={`${path}/view/${this.state.mailId}`} params={{ activeKey, readStatus: this.state.readStatus }} updateListData={updateListData} search={() => {listStore.onSearch({current: 1})}}/>
            );
          }}
        />
        <Route
          key="new"
          path={`${path}/new`}
          render={() => {
            return (
              <New path={`${path}/new`} params={newParam}/>
            );
          }}
        />
        <Route
          key="todo"
          path={`${path}/todo`}
          render={() => {
            return (
              <SetTodo path={`${path}/todo`} params={moveToParams} onSubmit={this.todo} />
            );
          }}
        />
        <Route
          key="moveTo"
          path={`${path}/moveTo`}
          render={() => {
            return (
              <MoveTo path={`${path}/moveTo`} params={moveToParams} onSubmit={this.moveTo} />
            );
          }}
        />
        <Route
          key="setTag"
          path={`${path}/setTag`}
          render={() => {
            return (
              <SetTag path={`${path}/setTag`} params={moveToParams} onSubmit={this.setTag} />
            );
          }}
        />
      </QueueAnim>
    );
  }
}